<template>
	<view class="publish">
		<view class="up">
			<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="9"
				uploadIcon="plus" class="yuan" :accept="'video/*,image/*'" ></u-upload>
		</view>
		<view class="title">
			<input type="text" value="" v-model="postsTotalVO.title" placeholder="填写标题会有更多赞哦~~~" />
		</view>
		<view class="con">
			<u--textarea v-model="postsTotalVO.content" placeholder="添加正文" height="200"></u--textarea>
		</view>
		<view class="gongkai" @click="open">
			<view class="public">
				{{status}}
			</view>
			<view class="gongkai-right">
				<image src="@/static/Myimg/rightjt.png" mode="aspectFit"></image>
			</view>
		</view>
		<view class="gongkai" @click="openTow">
			<view class="public">
				话题
			</view>
			<view class="gongkai-right">
				<image src="@/static/Myimg/rightjt.png" mode="aspectFit"></image>
			</view>
		</view>
		<u-popup :show="show" mode="bottom" @close="close">
			<view class="gongkai gaibian">
				<view class="public" @click="gaibian(0)">
					公开可见
				</view>
				<view class="gongkai-right">
					<image src="@/static/Myimg/rightjt.png" mode="aspectFit"></image>
				</view>
			</view>
			<view class="gongkai gaibian">
				<view class="public" @click="gaibian(1)">
					仅自己可见
				</view>
				<view class="gongkai-right">
					<image src="@/static/Myimg/rightjt.png" mode="aspectFit"></image>
				</view>
			</view>
		</u-popup>
		<u-popup :show="showtow" mode="bottom" @close="closetow">
			<view class="gongkai gaibian">
				<view class="public" @click="gaibian(0)">
					111111
				</view>
				<view class="gongkai-right">
					<image src="@/static/Myimg/rightjt.png" mode="aspectFit"></image>
				</view>
			</view>
		</u-popup>
		<view class="btn">
			<u-button type="primary" text="发布" color="#f47" shape="circle" @click="fabu"></u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList1: [],
				value1: "",
				show: false,
				showtow:false,
				status:"公开可见",
				postsTotalVO:{
					userId:uni.getStorageSync("id"),
					title:"",
					content:"",
					urls:"",
					mediaType:"",
					name:"穿搭"
				}
			}
		},
		methods: {
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			//posts/getUrl我这个接口是接收图片或者视频上传到我的腾讯云服务器上面并生成一条url，响应给前端，请帮我优化这个方法，让我可以上传视频  // 新增图片或视频
						  async afterRead(event) {
						    console.log(event);
						
						    let lists = Array.isArray(event.file) ? event.file : [event.file];
						    let fileList = this[`fileList${event.name}`];
						    let fileListLen = fileList.length;
						
						    // 更新文件列表状态为上传中
						    lists.forEach(item => {
						      fileList.push({
						        ...item,
						        status: 'uploading',
						        message: '上传中'
						      });
						    });
						
						    for (let i = 0; i < lists.length; i++) {
						      try {
						        const result = await this.uploadFilePromise(lists[i].url);
						        let item = fileList[fileListLen];
						        fileList.splice(fileListLen, 1, Object.assign(item, {
						          status: 'success',
						          message: '',
						          url: result
						        }));
						        fileListLen++;
						      } catch (error) {
						        console.error('上传文件失败:', error);
						        let item = fileList[fileListLen];
						        fileList.splice(fileListLen, 1, Object.assign(item, {
						          status: 'failed',
						          message: '上传失败'
						        }));
						        uni.showToast({
						          title: '上传失败，请重试',
						          icon: 'none'
						        });
						      }
						    }
						
						    lists.forEach(file => {
						      this.processing(file);
						    });
						
						    console.log(event);
						  },
						
						  processing(blobUrl) {
						    fetch(blobUrl.url)
						      .then(response => response.blob())
						      .then(blobData => {
						        const file = new File([blobData], blobUrl.name, { type: blobUrl.type });
						        console.log(file);
						
						        const formData = new FormData();
						        formData.append('file', file, file.name);
						
						        const fileType = file.type.startsWith('image') ? 'image' : file.type.startsWith('video') ? 'video' : 'unknown';
								console.log(file.type);
						        this.postsTotalVO.mediaType = fileType;
						        formData.append('mediaType', fileType);
						
						        const token = uni.getStorageSync("Authorization");
						        const headers = new Headers();
						        headers.append('Authorization', token);
						
						        const requestOptions = {
						          method: 'POST',
						          headers: headers,
						          body: formData
						        };
						
						        return fetch('http://106.54.33.247:8088/posts/getUrl', requestOptions);
						      })
						      .then(response => {
						        if (!response.ok) {
						          throw new Error('上传失败');
						        }
						        return response.json();
						      })
						      .then(data => {
						        console.log(data);
						        if (data.code === 200) {
						          this.postsTotalVO.urls = data.message;
						        } else if (data.code === 500) {
						          uni.showToast({
						            title: '上传失败',
						            icon: 'error',
						            duration: 1000
						          });
						        }
						      })
						      .catch(error => {
						        console.error('上传失败或获取 Blob 数据失败:', error);
						        uni.showToast({
						          title: '上传失败，请重试',
						          icon: 'none'
						        });
						      });
						  },
			uploadFilePromise(url) {
				// 这里是一个占位函数，可以根据需要实现文件上传的逻辑
				console.log(url);
			},
			fabu(){
				this.request("/posts/upPosts","post",this.postsTotalVO).then(res=>{
					console.log(res);
					if(res.data.code==200){
						uni.showToast({
							title: '发布成功',
							duration: 2000
						});
						uni.switchTab({
							url:'/pages/index/index'
						});
					}
				}).catch(err=>{
					console.log(err);
				});
			},
			close() {
				this.show = false;
			},
			open() {
				this.show = true;
			},
			closetow() {
				this.showtow = false;
			},
			openTow() {
				this.showtow = true;
			},
			gaibian(e){
				if(e==0){
					this.status="公开可见";
				}else {
					this.status="仅自己可见";
				}
				this.show=false;
			}
		}

	}
</script>


<style>
	.publish {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-evenly;
	}

	>>>.u-upload__button {
		border-radius: 35rpx;
	}

	.up {
		width: 90%;
		padding: 30rpx;
		display: flex;
		align-items: left;
	}

	.title {
		width: 90%;
		height: 100rpx;
		display: flex;
		border-bottom: solid 5rpx #e3e3e3;
	}

	.title input {
		width: 100%;
		height: 100%;
	}

	.con {
		width: 90%;
		border-bottom: solid 5rpx #e3e3e3;
	}

	.gongkai {
		width: 90%;
		height: 100rpx;
		/* background-color: black; */
		display: flex;
		justify-content: space-evenly;
		align-items: center;
	}

	.public {
		width: 50%;
		text-align: left;
	}

	.gongkai-right {
		width: 50%;
		height: 70%;
		display: flex;
		align-items: center;
		justify-content: right;
	}

	.gongkai-right image {
		width: 50%;
		height: 50%;
	}

	.gaibian {
		padding: 0 60rpx;
	}
	.btn{
		width: 90%;
		position: fixed;
		bottom: 0;
	}
</style>